from django.contrib.auth.backends import ModelBackend
from users.models import User
import re


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功后返回的数据
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# 定义方法判断用户是手机号还是用户名登录的
def get_user_by_account(account):
    try:
        if re.match(r'^1[3456789]\d{9}$', account):
            # 手机号
            user = User.objects.get(mobile=account)
        else:
            # 用户名
            user = User.objects.get(username=account)
    except Exception as e:
        return None

    return user


# 自定义类继承ModelBackend, 实现手机号，用户名均可登录
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        使用手机号或账号查询用户数据
        """
        user = get_user_by_account(username)
        # 如果用户存在，并且密码校验通过，响应user
        if user and user.check_password(password):
            return user
